package com.example.administrator.ygddriver.listen;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.appliedorder.AppliedOrderActivity;
import com.example.administrator.ygddriver.base.BaseFragment;
import com.example.administrator.ygddriver.base.BaseHint;
import com.example.administrator.ygddriver.base.JGRequestBean;
import com.example.administrator.ygddriver.base.LogInformationBean;
import com.example.administrator.ygddriver.base.UserBean;
import com.example.administrator.ygddriver.into.login.driverjoin.small.smallmessage.audit.AuditActivity;
import com.example.administrator.ygddriver.listen.grab.GrabActivity;
import com.example.administrator.ygddriver.liteorm.LiteOrmTools;
import com.example.administrator.ygddriver.netty.TcpClient;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.UrlValuse;

import java.util.HashMap;

public class ListenFragment extends BaseFragment {
    private RecyclerView mRv;
    private ListenAdapter mListenAdapter;
    private LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String c_token, c_driver;
    private String c_city;
    private GetNewBillReceiver getNewBillReceiver;

    @Override
    public int setLayout() {
        return R.layout.fragment_listen;
    }

    @Override
    public void initView(View view) {
        getNewBillReceiver = new GetNewBillReceiver();
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(UrlValuse.GET_NEW_BILL);
        context.registerReceiver(getNewBillReceiver, myIntentFilter);

        mLocationClient = new LocationClient(context);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        initOption();
        mRv = view.findViewById(R.id.fragment_listen_rv);
        mListenAdapter = new ListenAdapter(R.layout.item_fragment_listen, null);
        View view1 = LayoutInflater.from(context).inflate(R.layout.item_listen_adapter_sending_empty, null);
        mListenAdapter.setEmptyView(view1);
        mRv.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        mRv.setAdapter(mListenAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        mListenAdapter.setNewData(null);
        initMessage();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {   // 不在最前端显示 相当于调用了onPause();
            return;
        } else {  // 在最前端显示 相当于调用了onResume();
            mListenAdapter.setNewData(null);
            initMessage();
        }

    }

    @Override
    public void initData() {
        LiteOrmTools.getInformation(UserBean.class, context, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                if (data.getC_token() != null) {
                    c_token = data.getC_token();
                    c_driver = data.getC_id();
                }

            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        LiteOrmTools.getInformation(LogInformationBean.class, context, new LiteOrmTools.On<LogInformationBean>() {
            @Override
            public void hasData(LogInformationBean data) {
                c_city = data.getC_city();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        mLocationClient.start();
        mListenAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ListenRequestBean.ResultBean requestBean = (ListenRequestBean.ResultBean) adapter.getData().get(position);
                if (requestBean.getC_isbargaining().equals("1")) {
                    initGrabSingleHtml(c_driver, requestBean.getC_customer(), requestBean.getC_waybill(), String.valueOf(requestBean.getC_grab()), requestBean.getC_waybillnum(), requestBean.getC_valuation(), "0", requestBean.getC_isbargaining(), requestBean.getC_orderid(), c_token, position);
                } else if (requestBean.getC_isbargaining().equals("2")) {
                    Intent intent = new Intent(context, GrabActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putParcelable("requestBean", requestBean);
                    bundle.putInt("pos", position);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 0x002);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x002 && resultCode == 0x001) {
            data.getIntExtra("pos", 0);
            mListenAdapter.remove(data.getIntExtra("pos", 0));
            Intent intent = new Intent();
            intent.setAction(UrlValuse.GET_MAIN_SX);
            context.sendBroadcast(intent);
        }
    }

    //司机端抢单
    private void initGrabSingleHtml(String c_driver, final String c_customer, String c_id, String c_grab, String c_waybillnum, String c_valuation, String c_bargaining, String c_isbargaining, String c_orderid, String c_token, final int pos) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_driver", c_driver);
        hashMap.put("c_customer", c_customer);
        hashMap.put("c_id", c_id);
        hashMap.put("c_grab", c_grab);
        hashMap.put("c_waybillnum", c_waybillnum);
        hashMap.put("c_valuation", c_valuation);
        hashMap.put("c_bargaining", c_bargaining);
        hashMap.put("c_isbargaining", c_isbargaining);
        hashMap.put("c_orderid", c_orderid);
        hashMap.put("c_token", c_token);
        hashMap.put("c_type", "2");
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.GRAB_SINGLE, hashMap, GrabSingleRequestBean.class, new OkGoRequests.OnTrue<GrabSingleRequestBean>() {
            @Override
            public void hasData(GrabSingleRequestBean date) {
                if (date.isSuccess()) {
                    mListenAdapter.remove(pos);
                    // 抢单(可议价 c_account 用户端账号唯一标识  c_operation 操作类型)
                    String msg6 = "{c_account:" + c_customer + ",c_operation:6}&";
                    TcpClient instance_t = TcpClient.getInstance();
                    instance_t.sendMsgByByete(msg6);
                    Intent intent = new Intent();
                    intent.setAction(UrlValuse.GET_MAIN_SX);
                    context.sendBroadcast(intent);
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(context, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }
            }
        }, new OkGoRequests.OnError<GrabSingleRequestBean>() {
            @Override
            public void noData() {

            }
        });


    }

    //司机端听单列表查询
    private void initListDriverWaybillHtml(String c_driver, String c_customerlatitude, String c_customerlongitude, String c_token, String c_city, String limit, String offset) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("c_driver", c_driver);
        hashMap.put("c_customerlatitude", c_customerlatitude);
        hashMap.put("c_customerlongitude", c_customerlongitude);
        hashMap.put("c_token", c_token);
        hashMap.put("c_city", c_city);
        hashMap.put("c_type", "2");
        hashMap.put("limit", limit);
        hashMap.put("offset", offset);
        OkGoRequests.getInstance().putRequestAsync(UrlValuse.POST_API_DRIVER + UrlValuse.LIST_DRIVER_WAYBILL, hashMap, ListenRequestBean.class, new OkGoRequests.OnTrue<ListenRequestBean>() {
            @Override
            public void hasData(ListenRequestBean date) {
                if (date.isSuccess()) {
                    mListenAdapter.setNewData(date.getResult());
                } else {
                    BaseHint baseHint = new BaseHint.addHint().setParameter(context, "提示", date.getLocalizedMessage());
                    baseHint.show();
                }

            }
        }, new OkGoRequests.OnError<ListenRequestBean>() {
            @Override
            public void noData() {

            }
        });
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            double latitude = location.getLatitude();    //获取纬度信息
            double longitude = location.getLongitude();    //获取经度信息
            float radius = location.getRadius();    //获取定位精度，默认值为0.0f

            String coorType = location.getCoorType();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

            int errorCode = location.getLocType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            if (errorCode == 161 || errorCode == 61) {
                initListDriverWaybillHtml(c_driver, String.valueOf(latitude), String.valueOf(longitude), c_token, c_city, null, null);
                mLocationClient.stop();
            } else {
//                Toast.makeText(context, "定位失败", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void initOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false
        option.setIgnoreKillProcess(true);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)
        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false
        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位
        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false
        mLocationClient.setLocOption(option);
    }

    public class GetNewBillReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            mLocationClient.start();
        }
    }

    private void initMessage() {
        LiteOrmTools.getInformation(UserBean.class, context, new LiteOrmTools.On<UserBean>() {
            @Override
            public void hasData(UserBean data) {
                if (data.getC_token() != null) {
                    c_token = data.getC_token();
                    c_driver = data.getC_id();
                }

            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        LiteOrmTools.getInformation(LogInformationBean.class, context, new LiteOrmTools.On<LogInformationBean>() {
            @Override
            public void hasData(LogInformationBean data) {
                c_city = data.getC_city();
            }
        }, new LiteOrmTools.OFF() {
            @Override
            public void noData() {

            }
        });
        //网络数据刷新
        mLocationClient.start();
    }

}
